package com.atzongmaotan.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ClassName:    NIOFileChannel
 * Package:  com.atzongmaotan.nio
 * Description:
 *
 * @Author: interface
 * @Create: 2024/9/29 - 下午5:30
 * @Version: v1.0
 */
public class NIOFileChannel {
    public static void main(String[] args) throws IOException {
        writeFileChannel();
    }

    private static void writeFileChannel() throws IOException {
        //将数据从过 Buffer -> Channel -> IO流  -> 硬盘
        String message = "Hello FileChannel";
        FileOutputStream fos = new FileOutputStream("");
        FileChannel fileChannel = fos.getChannel();
        //分配内存空间
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //变成写入buffer
        byteBuffer.put(message.getBytes());
        //变成写出buffer
        byteBuffer.flip();
        //将buffer数据写出到Channel中
        fileChannel.write(byteBuffer);
        //关闭流
        fos.close();
    }
    private static void readFileChannel() throws IOException {
        File file = new File("");
        FileInputStream fis = new FileInputStream(file);
        FileChannel fileChannel = fis.getChannel();
        //分配内存空间
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //将channel中数据read到buffer中
        fileChannel.read(byteBuffer);
        //buffer变成write模式
        byteBuffer.flip();
        System.out.println(new String(byteBuffer.array()));
        fis.close();
    }
    private static void copyFileBuffer() throws IOException {
        //从这里获取文本
        FileInputStream fis = new FileInputStream(new File(""));
        FileChannel fipsc = fis.getChannel();
        //从这里写出文本
        FileOutputStream fos = new FileOutputStream(new File(""));
        FileChannel fopsc = fis.getChannel();
        //分配内存空间
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (true){
            //重置
            byteBuffer.clear();
            //read到buffer
            int read = fipsc.read(byteBuffer);
            if (read == -1){
                //数据读完
                break;
            }
            //切换模式
            byteBuffer.flip();
            //write到channel
            fopsc.write(byteBuffer);
        }
        fis.close();
        fos.close();
    }
    private static void copyFileChannel() throws IOException {
        //输入流
        FileInputStream fis = new FileInputStream(new File(""));
        FileChannel fipsc = fis.getChannel();
        //输出流
        FileOutputStream fos = new FileOutputStream(new File(""));
        FileChannel fopsc = fis.getChannel();

        //将输入流中数据copy到输出流中
        fopsc.transferFrom(fipsc, 0, fipsc.size());
        fipsc.close();
        fopsc.close();
        fis.close();
        fos.close();
    }
}
